package com.netwrok;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;


public class IoSession {
	ByteBuffer buffer = ByteBuffer.allocate(2048);

	SocketChannel channel;
	NetworkEvents network;
	SocketAddress address;
	
	IoSession(SocketChannel channel, NetworkEvents network) {
		this.channel = channel;
		this.network = network;
		
	}

	private boolean closed;

	public boolean isConnected() {
		if (closed) {
			return false;
		}
		boolean connected = channel.isConnected();
		if (!connected) {
			closed = true;
		}
		return connected;
	}

	public void close() {
		closed = true;
		IoQueues.getInstance().addCloseSession(this,network);
	}

	public void writeMsg(ResponseMsg msg) {
		if (closed) {
			return;
		}
		network.writeResponse(this, msg);
	}

	public SocketAddress getAddress() throws IOException {
		if (address==null && closed!=true) {
			address=channel.socket().getRemoteSocketAddress();
			
		}
		return address;
	}

}
